import React from 'react'

import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button,Message,Upload,Radio,TreeSelect,Modal} from 'antd';
import api from '../../../api/area';
import officeApi from '../../../api/office';
import apiAgentType from '../../../api/agentType';
import UserForm from '../../Form/User';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const { TextArea } = Input;

class OfficeForm extends React.Component {
  state = {
    confirmDirty: false,
    isOpen: false,
    cascaderData: [],
    isOpenCreateUser: false,
    type:0
  };

  handleSubmit = (e) => {
    const {close} = this.props;

    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.areaId=values.areaId[values.areaId.length-1];
        if(values.id){
          
          this.update(values);
        }else{
         
          this.add(values);
        }
      }
    });
  }

  setUser = (user) => {
    let newUser = {
      userId:user.id,
      userName:user.name
    };

    console.log(newUser);

    this.setState({
      user:newUser
    });
  }

  startCreateUser = () => {
    if (this.resetFields) this.resetFields();
    if (this.clearPho) this.clearPho();
    this.setState({
      isOpenCreateUser: true,
      user: null,
      clearForm: false,
    });
  }

  close = () => {
    this.setState({
      isOpenCreateUser: false,
      clearForm: true,
    });
  }

  update= (values) =>{
    officeApi.put('/updateOffice', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('修改成功！');
      const { close } = this.props;
      close();
     }else{
      Message.error(result.message);
     }
    });
  }
  add= (values) =>{
    officeApi.post('/addOffice', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('创建用户信息成功！');
      const { close } = this.props;
      close();
     }else{
      Message.error(result.message);
     }
    });
  }

  componentDidMount = () => {
    // 如果是代理商就查询代理商能够分配的代理商类型权限
    let {isAgent,isProperty,isAgentRoot} = this.props;
    if(isAgent || isAgentRoot){
      let {user} = this.props.profile;
      officeApi.get('getAgentTypeByOfficeId',{officeId:user.officeId}).then((data) => {
        const result = data.data.data;

        result.forEach(element => {
          element.id = element.agentTypeId;
          element.key = element.agentTypeId;
          element.title = element.agentTypeName;
          element.value = element.agentTypeName;
          element.name = element.agentTypeName;
        });

        this.setState({
          agentTypes:result
        });
      });
    } else {
      apiAgentType.get('/findAllAgentType').then((data) => {
        const result = data.data;
        result.forEach(element => {
          element.key = element.id;
          element.title = element.name;
        });
        
        this.setState({
          agentTypes:result
        });
      });
    }
  }

  initChildrenParams = (params) => {
    this.refresh = params.refresh;
  }

  areaLoadData = (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    targetOption.children = [];

    api.get('/getAreaByParent', { id: targetOption.value }).then((data) => {
      const result = data.data.data;

      if(!result){
        targetOption.loading = false;
        return false;
      }
      for(let i=0;i<result.length;i++){
          targetOption.children.push({
            value:result[i].id,
            label:result[i].name,
            isLeaf:result[i].type<5?false:true
          });
      }

      targetOption.loading = false;
      this.setState({
        cascaderData: [...this.state.cascaderData],
      });
    });
  }

  typeChange = (value) => {
    this.setState({
      type:value
    });
  }

  resetAgentType = () => {
    this.setState({
      type:0
    });
  }

  render() {
    const { getFieldDecorator,resetFields,setFieldsValue } = this.props.form;
    const { close , callbackParent ,parentOffice,office,areaData,areaParentIds,isAgent,isProperty,isAgentRoot} = this.props;
    const _this = this;
    const imageUrl = this.state.imageUrl;
    // 把重置表单的方法传给父亲
    callbackParent({
      resetFields:resetFields,
      resetAgentType:this.resetAgentType
    });

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };
    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
    })(
      <Select className="icp-selector">
        <Option value="86">+86</Option>
      </Select>
    );  

    let agentChildren = [];
    if(this.state.agentTypes){
      for (let i = 0; i < this.state.agentTypes.length; i++) {
        agentChildren.push(<Option key={this.state.agentTypes[i].id}>{this.state.agentTypes[i].name}</Option>);
      }
    }
    let defaultAgentType = [];
    if(office && office.agentTypes){
      for(let j = 0;j<office.agentTypes.length;j++){
        defaultAgentType.push(office.agentTypes[j].agentTypeId);
      }
    }

    let officeTypeDisable = {};
    if(isAgent || isProperty || isAgentRoot){
      officeTypeDisable = {disabled:true}
    }
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          {getFieldDecorator('id', {
              initialValue:office&&office.id?office.id:'',
            })(
              <Input type="hidden" />
            )}
          {getFieldDecorator('parentId', {
              initialValue:office&&office.parentId?office.parentId:(parentOffice&&parentOffice.id?parentOffice.id:0),
            })(
              <Input type="hidden" />
            )}
          <FormItem
            {...formItemLayout}
            label="所属上级机构"
            hasFeedback
          >
            {getFieldDecorator('parentName', {
              rules: [{
                required: true, message: '请选择机构名称后提交!',
              }],
              initialValue:office&&office.parentName?(office.parentName?office.parentName:'根机构'):(parentOffice&&parentOffice.id?parentOffice.name:'根机构'),
            })(
              <Input type="text" disabled/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="所属区域"
            hasFeedback
          >
            {getFieldDecorator('areaId', {
              rules: [{
                required: true, message: '请选择一个区域信息后提交!',
              }],
              initialValue:(office&&areaParentIds)?areaParentIds:null
            })(
              <Cascader
                options={areaData}
                loadData={this.areaLoadData}
                placeholder="请选择一个区域"
                changeOnSelect={true}
                notFoundContent={'已经没有内容啦'}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="机构用户"
            hasFeedback
          >
            {getFieldDecorator('userId', {
              rules: [],
              initialValue:this.state.user?this.state.user.userId:''
            })(
              <div>
                <Button type="primary" onClick={this.startCreateUser}>
                  <Icon type="user" />添加机构用户
                </Button>
                <Input type="hidden"/>
                {this.state.user?'　已添加:' + this.state.user.userName:''}
              </div>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="机构名称"
            hasFeedback
          >
            {getFieldDecorator('name', {
              rules: [{
                required: true, message: '请输入机构名称后提交!',
              }],
              initialValue:office&&office.name?office.name:''
            })(
              <Input type="text"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="机构地址"
            hasFeedback
          >
            {getFieldDecorator('address', {
              rules: [{
                required: true, message: '请输入机构地址后提交!',
              }],
              initialValue:office&&office.address?office.address:''
            })(
              <Input type="text"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="负责人"
            hasFeedback
          >
            {getFieldDecorator('master', {
              rules: [{
                required: true, message: '请输入责任人信息后提交!',
              }],
              initialValue:office?office.master:''
            })(
              <Input type="text"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="请输入电话号码"
          >
            {getFieldDecorator('phone', {
              rules: [{ required: true, message: '请输入电话号码后提交!' }],
              initialValue:office?office.phone:''
            })(
              <Input addonBefore={prefixSelector} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="机构类型"
          >
            {getFieldDecorator('type', {
              rules: [{ required: true, message: '必须选择一个机构类型!' }],
              initialValue:office?office.type:''
            })(
              <Select
                style={{ width: 200 }}
                placeholder="选择一个机构类型"
                onChange={this.typeChange}
                {...officeTypeDisable}
              >
                <Option value="1">代理商</Option>
                <Option value="2">分销商</Option>
                <Option value="3">物业</Option>
                <Option value="4">厂商</Option>
                <Option value="5">平台</Option>
              </Select>
            )}
          </FormItem>
          {this.state.type==1 || this.state.type==2 || (office && (office.type==1 || office.type==2))?
            <FormItem
              {...formItemLayout}
              label="代理商类型"
            >
              {getFieldDecorator('agentType', {
                rules: [{ required: true, message: '必须至少选择一个代理商类型!' }],
                initialValue:office?defaultAgentType:[]
              })(
                <Select mode="multiple" 
                placeholder={'请至少选择一个代理商类型'} dropdownStyle={{maxHeight:'240px'}}
                >
                  {agentChildren}
                </Select>
              )}
            </FormItem>:''
          }
          <FormItem
            {...formItemLayout}
            label="排序号"
          >
            {getFieldDecorator('sort', {
              initialValue:office?office.sort:''
            })(
              <Input type="text" placeholder="如不填排序号，则自动排到该等级末尾！"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="备注"
          >
            {getFieldDecorator('remarks')(
              <TextArea rows={4} />
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <div>
              <Button type="primary" htmlType="submit" style={{marginRight:'10px'}}>确定</Button>
              <Button onClick={close}>取消</Button>
            </div>
          </FormItem>
        </Form>
        <Modal
          title="创建用户"
          visible={this.state.isOpenCreateUser}
          onOk={this.close}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="1000"
          footer={null}
        >
          <UserForm user={this.state.user} isOfficeRelative={true} clearForm={this.state.clearForm} setUser={this.setUser} close={this.close} callbackParent={this.initChildrenParams} />
        </Modal>
      </div>
    );
  }
}

const WrappedOfficeForm = Form.create()(OfficeForm);
export default WrappedOfficeForm
